package com.docparser.processor;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 数学公式处理主协调器。
 * 负责协调各个专门的处理器处理不同类型的数学元素。
 */
public class MathFormulaProcessor extends BaseProcessor {
    private static final ProcessorCallback processorCallback = new ProcessorCallback() {
        @Override
        public void processElement(Element element, StringBuilder result) {
            processOMathArg(element, result);
        }
    };

    /**
     * 处理Office Math XML元素并转换为LaTeX格式。
     */
    public static void processOMath(Element mathElement, StringBuilder formula) {
        if (mathElement == null) return;
        
        NodeList children = mathElement.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child.getNodeType() != Node.ELEMENT_NODE) continue;
            
            processNode((Element) child, formula);
        }
    }

    /**
     * 处理单个节点。
     */
    private static void processNode(Element element, StringBuilder formula) {
        if (element == null) return;

        String nodeName = element.getNodeName();

        switch (nodeName) {
            case "m:func":
                FunctionProcessor.process(element, formula, processorCallback);
                break;
            case "m:r":
                processRun(element, formula);
                break;
            case "m:sSup":
                SuperscriptProcessor.process(element, formula, processorCallback);
                break;
            case "m:sSub":
                SubscriptProcessor.process(element, formula, processorCallback);
                break;
            case "m:rad":
                RadicalProcessor.process(element, formula, processorCallback);
                break;
            case "m:d":
                DelimiterProcessor.process(element, formula, processorCallback);
                break;
            case "m:f":
                FractionProcessor.process(element, formula, processorCallback);
                break;
            case "m:t":
                processRun(element, formula);
                break;
            default:
                processOMathArg(element, formula);
        }
    }

    /**
     * 处理文本运行元素。
     */
    private static void processRun(Element runElement, StringBuilder formula) {
        if (runElement == null) return;
        String text = runElement.getTextContent();
        if (text != null && !text.trim().isEmpty()) {
            TextContentProcessor.process(text, formula);
        }
    }

    /**
     * 处理数学元素参数。
     */
    private static void processOMathArg(Element element, StringBuilder result) {
        if (element == null) return;
        
        NodeList children = element.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child.getNodeType() == Node.ELEMENT_NODE) {
                Element childElement = (Element) child;
                // 处理负号
                if (childElement.getTextContent().equals("−")) {
                    result.append("-");
                } else {
                    processNode(childElement, result);
                }
            }
        }
    }

    /**
     * 修复LaTeX公式的常见问题。
     */
    private static String fixCommonIssues(String formula) {
        return formula
            // 移除多余的反斜杠
            .replaceAll("\\\\\\{", "{")
            .replaceAll("\\\\\\}", "}")
            // 修复分式括号
            .replace("\\frac\\{", "\\frac{")
            .replace("\\}\\{", "}{")
            // 处理数学操作符
            .replace("\\pm\\", "\\pm ")
            .replace("\\cdot\\", "\\cdot ")
            // 修复负号
            .replace("−", "-")
            // 移除多余的空格
            .replaceAll("\\s+", " ")
            .trim();
    }

    /**
     * 清理并格式化LaTeX公式。
     */
    public static String cleanFormula(String formula) {
        if (formula == null) return "";
        String fixed = fixCommonIssues(formula);
        return FormulaFormatter.format(fixed);
    }
}
